package com.cuile.littletools.create

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.CameraUpdateFactory
import com.amap.api.maps2d.MapView
import com.amap.api.maps2d.model.CameraPosition
import com.amap.api.maps2d.model.LatLng
import com.amap.api.maps2d.model.MarkerOptions
import com.amap.api.maps2d.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.cuile.littletools.LittleToolsContacts
import com.cuile.littletools.R


/**
 * Created by cuile on 18-10-16.
 *
 */
class CreateQrDialog : DialogFragment() {

    private var createType = ""

    private var layoutView: View? = null

    private var mapView: MapView? = null
    private var aMap: AMap? = null



    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        createType = arguments?.getString(LittleToolsContacts.CREATE_QR_TYPE)?: throw IllegalArgumentException("created qr type is needed!")

        layoutView = getDialogView(createType)

        if (createType == getString(R.string.location_qr)) {
            mapView = layoutView?.findViewById(R.id.curMap)
            mapView?.onCreate(savedInstanceState)
            initMap()
        }

        val builder = AlertDialog.Builder(context!!)
        return builder.setView(layoutView)
                .setPositiveButton(getString(R.string.create)) { _, _ ->
                    val qrContent = getQrContent()
                    setQrDatas(qrContent)
                    dialog.cancel()
                }
                .setNegativeButton(getString(R.string.cancel)) { _, _ ->
                    dialog.cancel()
                }
                .create()
    }

    private fun getDialogView(createType: String): View? {
        val layoutId = when (createType) {
            getString(R.string.contact_qr) -> R.layout.view_contact_qr
            getString(R.string.email_qr) -> R.layout.view_email_qr
            getString(R.string.msg_qr) -> R.layout.view_msg_qr
            getString(R.string.net_qr) -> R.layout.view_net_qr
            getString(R.string.phone_qr) -> R.layout.view_phone_qr
            getString(R.string.wifi_qr) -> R.layout.view_wifi_qr
            getString(R.string.location_qr) -> R.layout.view_location_qr
            getString(R.string.barcode) -> R.layout.view_bar_code
            else -> R.layout.view_txt_qr
        }

        return activity?.layoutInflater?.inflate(layoutId, null)
    }

    private fun getQrContent(): String = when (createType) {
        getString(R.string.contact_qr) -> {
            val name = layoutView?.findViewById<EditText>(R.id.contactName)?.text.toString()
            val phoneNum = layoutView?.findViewById<EditText>(R.id.contactNum)?.text.toString()
            val qqNum = layoutView?.findViewById<EditText>(R.id.contactQQ)?.text.toString()
            val email = layoutView?.findViewById<EditText>(R.id.contactEmail)?.text.toString()
            val company = layoutView?.findViewById<EditText>(R.id.contactCompany)?.text.toString()
            val post = layoutView?.findViewById<EditText>(R.id.contactPost)?.text.toString()
            val addr = layoutView?.findViewById<EditText>(R.id.contactAddr)?.text.toString()

            "MECARD:TEL:$phoneNum;EMAIL:$email;NOTE:$qqNum;N:$name;ORG:$company;TIL:$post;ADR:$addr;"
        }
        getString(R.string.email_qr) -> {
            val email = layoutView?.findViewById<EditText>(R.id.emailAddr)?.text.toString()

            "mailto:$email"
        }
        getString(R.string.msg_qr) -> {
            val phoneNum = layoutView?.findViewById<EditText>(R.id.msgDesNum)?.text.toString()
            val content = layoutView?.findViewById<EditText>(R.id.msgContent)?.text.toString()

            "smsto:$phoneNum:$content"
        }
        getString(R.string.net_qr) -> {
            val url = layoutView?.findViewById<EditText>(R.id.netAddr)?.text.toString()

            "URLTO:$url"
        }
        getString(R.string.phone_qr) -> {
            val phone = layoutView?.findViewById<EditText>(R.id.phoneNum)?.text.toString()

            "tel:$phone"
        }
        getString(R.string.wifi_qr) -> {
            val name = layoutView?.findViewById<EditText>(R.id.wifiName)?.text.toString()
            val pwd = layoutView?.findViewById<EditText>(R.id.wifiPwd)?.text.toString()

            "WIFI:S:$name;T:WPA;P:$pwd;"
        }
        getString(R.string.location_qr) -> {

            if (selectedLatLng == null) {
                ""
            } else {
                // val qrStr1 = "GEO:${selectedLatLng!!.longitude},${selectedLatLng!!.latitude}"   //经纬度

                "https://uri.amap.com/marker?position=${selectedLatLng!!.longitude},${selectedLatLng!!.latitude}"

            }
        }
        getString(R.string.barcode) -> {
            val code = layoutView?.findViewById<EditText>(R.id.barcodeNum)?.text.toString()
            code
        }
        else -> {
            val txt = layoutView?.findViewById<EditText>(R.id.txtContent)?.text.toString()

            txt
        }

    }

    private fun setQrDatas(qrContent: String) {
        if (targetFragment == null) return

        val intent = Intent().apply { putExtra(LittleToolsContacts.CREATE_RESULT_KEY, qrContent) }
        targetFragment!!.onActivityResult(LittleToolsContacts.CREATE_REQUEST_CODE, LittleToolsContacts.CREATE_RESULT_CODE, intent)
    }

    private fun initMap() {
        if (aMap == null)
            aMap = mapView?.map

        val myLocationStyle = MyLocationStyle().apply {
            myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
        }

        aMap?.setMyLocationStyle(myLocationStyle)
        aMap?.isMyLocationEnabled = true
        aMap?.uiSettings?.isMyLocationButtonEnabled = true
        aMap?.setOnMyLocationChangeListener {
            aMap?.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition(LatLng(it.latitude,it.longitude),10f,0f,0f)))
        }
        aMap?.setOnMapClickListener {
            aMap?.addMarker(MarkerOptions().position(it).title("选中位置").snippet("坐标：(${it.latitude},${it.longitude})\n点击切换"))?.showInfoWindow()
            selectedLatLng = it
        }
        aMap?.setOnInfoWindowClickListener {
            if (selectedLatLng != null) {
                if (it.snippet.contains("坐标：(")) {
                    GeocodeSearch(context).apply {
                        getFromLocationAsyn(RegeocodeQuery(LatLonPoint(selectedLatLng!!.latitude, selectedLatLng!!.longitude),200f, GeocodeSearch.AMAP))
                    }.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener{
                        override fun onRegeocodeSearched(result: RegeocodeResult?, p1: Int) {
                            if (p1 == 1000) {
                                val adress = result?.regeocodeAddress?.formatAddress
                                it.snippet = "$adress\n点击切换"
                                it.showInfoWindow()
                            }
                        }
                        override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {}
                    })

                } else {
                    it.snippet = "坐标：(${selectedLatLng?.latitude},${selectedLatLng?.longitude})\n点击切换"
                    it.showInfoWindow()
                }
            }
        }
    }

    private var selectedLatLng: LatLng? = null

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mapView?.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        mapView?.onResume()
    }

    override fun onPause() {
        super.onPause()
        mapView?.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mapView?.onDestroy()
    }
}